<style scoped>
  .weui-form-preview__hd label, .weui-form-preview__hd em {
    font-size: .9em !important;
  }
  .weui-loadmore_line .weui-loadmore__tips {
    background-color: #eee;
  }
  .rj-cell.max span{
    font-size: 16px;
    padding-right: 20px;
  }
  .rj-cell label {
    color: #333;
    font-size: 14px;
    width: 44%;
    display: inline-block;
    padding: 5px 3%;
    text-align: right;
  }
  .rj-cell span {
    font-size: 14px;
    color: #333;
    display: inline-block;
    width: 50%;
  }
  .rj-cell.note label{
    float: left;
  }
  .rj-cell.note span{
    width: 80%;
    display: inline-block;
  }
  .weui-cells {
    margin-top: 0;
  }
  .weui-cells_form {
    background: #fbfbfb;
  }
  .weui-cell {
    background: #fff;
  }
  .weui-cells__title {
    text-align: left;
  }
  .oitem {
    padding: 3px;
  }
  #acts span {
    font-size: 14px;
  }
  .halfbtn {
    display: inline-block;
    width: 49%;
  }
  .weui-label {
    text-align: left;
  }

  .weui_uploader_input_wrp {
    float: left;
    position: relative;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 77px;
    height: 77px;
    border: 1px solid #D9D9D9;
  }
  .weui_uploader_hd {
    padding-top: 0;
    padding-right: 0;
    padding-left: 0;
  }
  .weui_uploader_files {
    list-style: none;
  }
  .weui_uploader_input_wrp:before {
    width: 2px;
    height: 39.5px;
  }
  .weui_uploader_input_wrp:before, .weui_uploader_input_wrp:after {
    content: " ";
    position: absolute;
    top: 50%;
    left: 50%;
    -webkit-transform: translate(-50%, -50%);
    transform: translate(-50%, -50%);
    background-color: #D9D9D9;
  }
  .weui_uploader_input {
    position: absolute;
    z-index: 1;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    opacity: 0;
    -webkit-tap-highlight-color: rgba(0, 0, 0, 0);
  }
  .weui_uploader_input_wrp:after {
    width: 39.5px;
    height: 2px;
  }
  .weui_uploader_bd {
    overflow: hidden;
  }
  .weui_cell {
    padding: 10px 15px;
    position: relative;
    display: -webkit-box;
    display: -webkit-flex;
    display: -ms-flexbox;
    display: flex;
    -webkit-box-align: center;
    -webkit-align-items: center;
    -ms-flex-align: center;
    align-items: center;
    background: #fff;
  }
  .examine >>> .weui-uploader_files {
    list-style: none;
    overflow-y: hidden;
  }
  .examine >>> .weui-uploader_file {
    float: left;
    margin-right: 9px;
    margin-bottom: 9px;
    width: 79px;
    background: no-repeat 50%;
    background-size: cover;
  }
</style>
<template>
  <div class="examine">
    <div class="rj-wrap">
      <!--      <div class="logsbtn" @click="openLogs"><img src="@/assets/icon-history.png" style="width: 20px" /></div>-->
      出库
      <a href="javascript:;" @click="$router.back(-1)" style="position: absolute; left: 10px; top: 8px">
        <img src="@/assets/back.png" style="width: 20px" />
      </a>
    </div>
    <div class="weui-cells weui-cells_form">
      <form action="" method="post" id="formid">
        <div class="cellgroup">
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">编号</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="baseInfo.code" name="">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">类型</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" readonly :value="baseInfo.type == 6 ? '出库' : '入库'" name="">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">{{baseInfo.type == 1 ? '调出' : ''}}库房</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly :value="baseInfo.fromsrname">
            </div>
          </div>
          <div class="weui-cell" v-if="baseInfo.type == 1">
            <div class="weui-cell__hd"><label class="weui-label">调入库房</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly :value="baseInfo.tosrname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">重量</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input inlinput1" readonly name="" :value="baseInfo.shiftweight">
              <input class="weui-input inlinput2" type="text" readonly value="吨">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">申请人</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly name="" :value="baseInfo.applyname">
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">申请时间</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" readonly type="text" name="" :value="baseInfo.createtime">
            </div>
          </div>
        </div>
        <div class="oitem" v-for="(product, index) in baseInfo.items" :key="product.guid">
          <input type="hidden" :name="'items[' + index + '].scrapitemid'" :value="product.guid" />
          <input type="hidden" :name="'items[' + index + '].productguid'" :value="product.productguid" />
          <input type="hidden" :name="'items[' + index + '].spguid'" :value="product.spguid" />
          <!--          <input type="hidden" :name="'items[' + index + '].shrguid'" :value="product.shguid" />-->
          <div class="weui-cells__title">货品明细 {{index + 1}}</div>
          <!--          <div class="weui-cell fir">-->
          <!--            <div class="weui-cell__hd"><label class="weui-label">{{baseInfo.type == 1 ? '调出' : ''}}库间</label></div>-->
          <!--            <div class="weui-cell__bd">-->
          <!--              <input class="weui-input" type="text" name="" readonly="true" :value="product.fromshname">-->
          <!--            </div>-->
          <!--          </div>-->
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">货品类型</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly="true" :value="getTypeName(product.type)">
            </div>
          </div>
          <div class="weui-cell fir">
            <div class="weui-cell__hd"><label class="weui-label">产品</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input" type="text" name="" readonly="true" :value="product.product">
            </div>
          </div>
<!--          <div class="weui-cell" v-if="product.type != 1">-->
<!--            <div class="weui-cell__hd"><label class="weui-label">规格</label></div>-->
<!--            <div class="weui-cell__bd">-->
<!--              <input class="weui-input" type="text" name="" readonly="true" :value="product.spname">-->
<!--            </div>-->
<!--          </div>-->
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">库间</label></div>
            <div class="weui-cell__bd">
              <input type="hidden" ref="fromshname" name="fromshname">
              <select class="weui-select house" :name="'items[' + index + '].shrguid'">
                <option value="" disabled>请选择</option>
                <option v-for="(item, i) in autoHouses(index)" :key="item.storeroomguid" :value="item.storeroomguid" :data-storeqty="item.storeqty" :data-house="item.storeroomName">{{item.storeroomName}} ({{item.storeqty}}吨)</option>
              </select>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__hd"><label class="weui-label">重量</label></div>
            <div class="weui-cell__bd">
              <input class="weui-input weight inlinput1" type="number" readonly :name="'items[' + index + '].weight'" :value="product.shiftweight" placeholder="请输入重量" @change="getWei($event, product.shiftweight, index)" :ref="'weight' + index">
              <input class="weui-input inlinput2" type="text" readonly value="吨">
            </div>
          </div>
        </div>
        <div ref="actHtml" class="fixcont">
          <div class="weui_cell">
            <div class="weui_cell_bd weui_cell_primary">
              <div class="weui_uploader">
                <div class="weui_uploader_hd weui_cell" style="padding-left: 0;">
                  <div class="weui_cell_bd weui_cell_primary" id="examine">单据上传</div>
                  <div class="weui_cell_ft"></div>
                </div>
                <div class="weui_uploader_bd">
                  <ul class="weui-uploader_files" id="images">
                    <li class="weui-uploader_file" v-for="(img, index) in images.serverId" :id="img"  @click=del(img) ><img :src="images.srcStr[index]" width="85" /></li>
                  </ul>
                  <div class="weui_uploader_input_wrp">
                    <input type="button" id="selectImage"  class="weui_uploader_input" >
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div class="weui-cell">
            <div class="weui-cell__bd">
              <textarea class="weui-textarea opinion" id="opinion" name="opinion" placeholder="请输入意见内容" rows="2"></textarea>
            </div>
          </div>
          <div class="weui-btn-area">
            <a class="weui-btn weui-btn_primary halfbtn subbtn" href="javascript:" @click="postForm">提交</a>
            <a class="weui-btn weui-btn_primary halfbtn subbtn" v-if="refuseflag == 1" href="javascript:" @click="rejectIt">拒绝</a>
            <a class="weui-btn weui-btn_primary halfbtn" v-else  href="javascript:" @click="$router.back(-1)" id="sub">返回</a>
          </div>
        </div>
      </form>
    </div>
    <div id="bmlogs">
      <OperationLogs2 :nodeid="nodeid" :orderid="id" :srguid="baseInfo.status <= 15 ? baseInfo.fromsrguid : baseInfo.tosrguid" :departid="''"></OperationLogs2>
    </div>
  </div>
</template>

<script>
  import wx from 'weixin-js-sdk';
  import OperationLogs2 from '../../common/OperationLogs2'
  import TransOperationLogs2 from '../../common/TransOperationLogs2'

  export default {
    name: 'TransferOutStoreRm',
    data () {
      return {
        openid: localStorage.openid,
        id: '',
        type: '',
        baseInfo: {},
        wxParams: {},
        nodeid: '',
        annex: '',
        houses: [],
        fromshguid: '',
        images: {
          serverId: [],
          srcStr: [],
        },
        refuseflag: '',
        refuseNodes: [],
        tranferParam: '',
        artoken: ''
      }
    },
    components: {
      OperationLogs2,
      TransOperationLogs2
    },
    mounted () {
      //根据userid和时间戳生成唯一字符串
      this.artoken = this.createToken();
      //提交操作定位到页面底部
      //$('#bmlogs').css('margin-bottom', this.$refs.actHtml.offsetHeight)

      this.id = this.$route.query.guid;
      this.nodeid = this.$route.query.nodeid;
      this.annex = this.$route.query.annex;
      this.type = this.$route.query.type;
      this.getBaseInfo(this.id, this);

      this.refuseflag = this.$route.query.refuseflag;
      this.getRefuseNodes();

      //判断输入重量是否超限
      $('#formid').on('change', '.weight', function () {

      })
    },
    updated () {
      $('.house').change(function () {
        if ($(this).find('option:selected').data('storeqty') <= 0) {
          this.toastText('库存不符合要求，请重新选库间!');
          $(this).val('');
        } else {
          // let house = $(this).find('option:selected').data('house');
          // $(this).prev().val(house);
        }
      })
    },
    watch: {
      // 'fromshguid': function (val) {
      //   this.$refs.fromshname.value = $('#fromsh').find('option:selected').text();
      // },
    },
    methods: {
      getWei: function(val, wei, index) {
        if (val.target.value > wei * (1 + this.tranferParam / 100)) {
          this.toastText('出库重量不能大于: 订单重量 * ' + (100+this.tranferParam) + '%');
          this.$refs['weight' + index][0].value = '';
        }
      },
      wxConfig: function(wxParams) {
        wx.config({
          debug: false,            // 开启调试模式,调用的所有api的返回值会在客户端alert出来，若要查看传入的参数，可以在pc端打开，参数信息会通过log打出，仅在pc端时才会打印。
          appId: wxParams.appid,    // 必填，公众号的唯一标识
          timestamp: wxParams.timestamp,  // 必填，生成签名的时间戳
          nonceStr: wxParams.nonceStr, // 必填，生成签名的随机串
          signature: wxParams.signature,// 必填，签名
          jsApiList: ['scanQRCode', 'chooseImage', 'uploadImage'] // 必填，需要使用的JS接口列表
        });
      },
      wxUoloadImage: function(that) {
        let cthis = this;
        //wx.ready(function(){
        // config信息验证后会执行ready方法，所有接口调用都必须在config接口获得结果之后，config是一个客户端的异步操作，所以如果需要在页面加载时就调用相关接口，则须把相关接口放在ready函数中调用来确保正确执行。对于用户触发时才调用的接口，则可以直接调用，不需要放在ready函数中。
        document.querySelector('#selectImage').onclick = function () {
          wx.chooseImage({
            success: function (res) {
              $(function(){
                $.each( res.localIds, function(i, n){
                  wx.uploadImage({
                    localId: n,
                    isShowProgressTips: 1,
                    success: function (res) {
                      if (that.checkCore() == 'ios') {
                        wx.getLocalImgData({
                          localId: n, // 图片的localID
                          success: function (res2) {
                            cthis.$nextTick(function () {
                              cthis.images.srcStr.push(res2.localData);
                            })
                          }
                        });
                      } else {
                        cthis.$nextTick(function () {
                          cthis.images.srcStr.push(n);
                        })
                      }

                      cthis.images.serverId.push(res.serverId);
                    },
                    fail: function (res) {
                      $.alert(JSON.stringify(res));
                    }
                  });
                });
              });
            }
          });
        };
        //});

      },
      del: function (id){
        let cthis = this;
        $.actions({
          actions: [{
            text: "删除",
            onClick: function() {
              $.confirm("确定删除?", function() {
                //点击确认后的回调函数
                //删掉id
                var ids = cthis.images.serverId;
                var a =  ids.indexOf(id);
                cthis.$nextTick(function () {
                  cthis.images.serverId.splice(a,1);
                  cthis.images.srcStr.splice(a,1);
                })
                //$("#"+id).hide();
              }, function() {
                //点击取消后的回调函数
              });
            }
          }
          ]
        });
      },
      checkCore:function() {
        var u = navigator.userAgent;
        //var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Linux') > -1;//g
        var isIOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/);   //ios终端
        if (isIOS) {
          return 'ios';
        } else  {
          return 'android';
        }
      },
      autoHouses: function(no) {
        return this.houses['house' + no];
      },
      getBaseInfo: function(id, that) {
        this.axios({
          method: 'post',
          url: '/produce/Transferapply!getUpImagInfo.action',
          params: {applyid: id, url: location.href.split("#")[0]}
        }).then(response => {
          if (response.data.msg == 'success') {
            this.baseInfo = response.data.apply;
            let apply = response.data.apply;
            let items = response.data.apply.items;
            this.tranferParam = parseFloat(response.data.tranferParam);
            if (items.length != 0) {
              for (let i=0; i<items.length; i++) {
                this.$nextTick(function () {
                  //获取库间
                  this.getHouses(items[i].type, apply.orgid, apply.fromsrguid, items[i].productguid, items[i].spguid, i);
                })
              }
            }
            let wxParams = response.data.params;
            //配置微信公众号参数
            this.wxConfig(response.data.params);
            //上传
            this.wxUoloadImage(that);
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
        });
      },
      getHouses: function(type, orgid, roomid, productid, specid = '', index) {
        this.axios({
          method: 'get',
          url: '/sales/Whoutform!getPLInfo.action',
          params: {orgid: orgid, strmid: roomid, picktype: type, productid: productid, spec: specid}
        }).then((response) => {
          if (response.data.houses != undefined) {
            let data = response.data;
            this.$set(this.houses, 'house' + index, data.houses);
            //this['house' + index] = data.houses;
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastText("获取库间数据失败");
          }

        })
      },
      postForm: function () {
        let that = this;

        if (!this.checkEmy('weight')) {
          this.toastText('重量不能为空！');
          return false;
        } if (!this.checkEmy('house')) {
          this.toastText('库间不能为空！');
          return false;
        } else if (this.annex.indexOf('whout') > -1 && this.images.serverId.length == 0) {
          this.toastText('单据不能为空！');
          return false;
        }
        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        postData = this.serialize2Obj($("#formid").serializeArray());
        postData.nodeid = this.nodeid;
        postData.imageids = this.images.serverId.join(',');
        postData.applyid = this.id;
        this.axios({
          headers: {
            'artoken': this.artoken
          },
          method: 'post',
          url: '/produce/Whoutform!tranferWhout.action',
          params: postData
        }).then(response => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'repeatSubmit') {
            this.toastText('重复提交');
          } else if (response.data.msg == 'success') {
            this.toastSuccess('提交成功!');
            this.$router.push({name: 'PlantTransApplyList', query:{type: this.type}});
          } else if (response.data.msg == 'nowhinfo') {
            this.toastText('库存不足！');
            this.artoken = this.createToken();
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
            this.artoken = this.createToken();
          } else if (response.data.msg == 'outlogin') {
            this.toastText('请重新登录');
            this.artoken = this.createToken();
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
            this.artoken = this.createToken();
          } else {
            this.toastError('系统错误');
            this.artoken = this.createToken();
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
      /**
       * 20200311 添加调拨类型
       * liukx
       * @returns {string}
       */
      getTypeName: function(type) {
        let name = '';
        switch (type) {
          case 1:
            name = '原料';
            break;
          case 2:
            name = '成品';
            break;
          case 3:
            name = '次品';
            break;
        }
        return name;
      },
      openLogs: function() {
        this.$router.push({name: 'OperationLogs2', query: {orderid: this.id, srguid: this.baseInfo.fromsrguid, departid: ''}});
      },

      getRefuseNodes: function() {
        let that = this;
        this.axios({
          method: 'get',
          url: '/sales/Flowtempnode!getRefuseNodes.action',
          params: {orderid: this.id, nodeid: this.nodeid}
        }).then(response => {

          if (response.data.msg == 'success') {
            this.refuseNodes = response.data.optNodes.map(function (item) {
              return {text: item.name,
                onClick: function() {
                  $.confirm("确定要将订单回退到 " + item.name + " 节点？", function() {
                    that.doReject(item.guid, item.name, item.operatorid);
                  })
                }};
            });
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastText('获取可回退节点数据失败!');
          }
        });
      },
      rejectIt: function () {
        if (!this.checkEmy('opinion')) {
          this.toastText('意见不能为空！');
          return false;
        }
        if (this.refuseNodes.length > 0) {
          $.actions({
            title: '选择回退节点',
            actions: this.refuseNodes
          });
        } else {
          this.toastText('无可回退节点！');
          return false;
        }
      },
      doReject: function (refuseNodeid, refuseNodename, refuseOperatorid) {
        let that = this;

        //防止重复提交
        $('.subbtn').attr("disabled",true).css("pointer-events","none");
        //显示提交状态
        $.showLoading("正在提交");

        let postData = {};
        // postData.imgids = this.images.serverId.join(',');
        postData.imgids = '';
        postData.transferid = this.id;
        postData.opinion = ($('#opinion').val() || '') + ' 退回到' + refuseNodename;
        postData.nodeid = this.nodeid;
        postData.refuseNodeid = refuseNodeid;
        postData.backUserid = refuseOperatorid;
        this.axios({
          method: 'post',
          url: '/produce/Transferapply!refuse.action',
          params: postData
        }).then((response) => {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();

          if (response.data.msg == 'success') {
            this.toastSuccess('提交成功!');
            this.$router.push({name: 'TransferApplyList', query:{type: this.type}});
          } else if (response.data.msg == 'canotopt') {
            this.toastText('不允许的操作！');
          } else if (response != undefined && response.data != undefined && response.data.msg == 'sessionTimeOut') {
            //不不设置提示
          } else {
            this.toastError('系统错误');
          }
        }).catch(function (error) {
          //恢复提交按钮可点击
          $('.subbtn').attr('disabled', false).css("pointer-events","auto");
          //关闭提交状态
          $.hideLoading();
          that.toastError('系统错误');
        });
      },
    }
  }
</script>
